package top.broncho.gank.ui.fragment

import android.content.Intent
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import top.broncho.gank.R
import top.broncho.gank.adapter.HomeAdapter
import top.broncho.gank.app.App
import top.broncho.gank.bean.Article
import top.broncho.gank.bean.ArticleResponseBody
import top.broncho.gank.constant.Constant
import top.broncho.gank.databinding.FragmentSearchListBinding
import top.broncho.gank.ext.showSnackMsg
import top.broncho.gank.ext.showToast
import top.broncho.gank.ui.activity.ContentActivity
import top.broncho.gank.ui.activity.LoginActivity
import top.broncho.gank.utils.NetWorkUtil
import top.broncho.gank.widget.SpaceItemDecoration
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import kotlinx.android.synthetic.main.fragment_search_list.*
import top.broncho.mvvm.base.BaseDiFragment

class SearchListFragment : BaseDiFragment<FragmentSearchListBinding>() {

    companion object {
        fun getInstance(bundle: Bundle): SearchListFragment {
            val fragment = SearchListFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    private val viewModel by viewModels<SearchListViewModel> { viewModelFactory }
    /**
     * 每页数据的个数
     */
    protected var pageSize = 20

    /**
     * 是否是下拉刷新
     */
    protected var isRefresh = true

    /**
     * LinearLayoutManager
     */
    protected val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireContext())
    }

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireContext())
    }

    /**
     * RefreshListener
     */
    protected val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        onRefreshList()
    }

    /**
     * LoadMoreListener
     */
    protected val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        onLoadMoreList()
    }


    private var mKey = ""

    /**
     * datas
     */
    private val datas = mutableListOf<Article>()

    /**
     * Adapter
     */
    private val mAdapter: HomeAdapter by lazy {
        HomeAdapter(activity, datas)
    }


    fun hideLoading() {
        if (isRefresh) {
            mAdapter.setEnableLoadMore(true)
        }
    }

    fun showError(errorMsg: String) {
        if (isRefresh) {
            mAdapter.setEnableLoadMore(true)
        } else {
            mAdapter.loadMoreFail()
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_search_list

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        viewModel.article.observe({ lifecycle }) {
            swipeRefreshLayout.isRefreshing = false
            if (it.isFailure) {
                showError(it.exceptionOrNull().toString())
                return@observe
            }
            mLayoutStatusView?.showContent()
            showArticles(it.getOrThrow())
        }

        viewModel.collect.observe({ lifecycle }) {
            showCollectSuccess(it.isSuccess)
        }
        viewModel.cancel.observe({ lifecycle }) {
            showCancelCollectSuccess(it.isSuccess)
        }
    }

    fun initView(view: View) {
        mLayoutStatusView = multiple_status_view
        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        mKey = arguments?.getString(Constant.SEARCH_KEY, "") ?: ""

        recyclerView.adapter = mAdapter

        mAdapter.run {
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
            onItemClickListener = this@SearchListFragment.onItemClickListener
            onItemChildClickListener = this@SearchListFragment.onItemChildClickListener
            // setEmptyView(R.layout.fragment_empty_layout)
        }

        floating_action_btn.setOnClickListener {
            scrollToTop()
        }
    }

    override fun onResume() {
        super.onResume()
        if (viewModel.article.value == null) {
            lazyLoad()
        }
    }

    fun lazyLoad() {
        mLayoutStatusView?.showLoading()
        viewModel.queryBySearchKey(0, mKey)
    }

    fun onRefreshList() {
        mAdapter.setEnableLoadMore(false)
        viewModel.queryBySearchKey(0, mKey)
    }

    fun onLoadMoreList() {
        val page = mAdapter.data.size / pageSize
        viewModel.queryBySearchKey(page, mKey)
    }

    fun showCancelCollectSuccess(success: Boolean) {
        if (success) {
            showToast(getString(R.string.cancel_collect_success))
        }
    }

    fun showCollectSuccess(success: Boolean) {
        if (success) {
            showToast(getString(R.string.collect_success))
        }
    }

    fun showArticles(articles: ArticleResponseBody) {
        articles.datas.let {
            mAdapter.run {
                if (isRefresh) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                pageSize = articles.size
                if (articles.over || articles.curPage == articles.pageCount) {
                    loadMoreEnd(isRefresh)
                } else {
                    loadMoreComplete()
                }
            }
        }
        if (mAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    fun scrollToTop() {
        recyclerView.run {
            if (linearLayoutManager.findFirstVisibleItemPosition() > 20) {
                scrollToPosition(0)
            } else {
                smoothScrollToPosition(0)
            }
        }
    }

    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (datas.size != 0) {
            val data = datas[position]
            ContentActivity.start(activity, data.id, data.title, data.link)
        }
    }

    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener =
        BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
            if (datas.size != 0) {
                val data = datas[position]
                when (view.id) {
                    R.id.iv_like -> {
                        if (isLogin) {
                            if (!NetWorkUtil.isNetworkAvailable(App.context)) {
                                showSnackMsg(resources.getString(R.string.no_network))
                                return@OnItemChildClickListener
                            }
                            val collect = data.collect
                            data.collect = !collect
                            mAdapter.setData(position, data)
                            if (collect) {
                                viewModel.cancelCollectArticle(data.id)
                            } else {
                                viewModel.addCollectArticle(data.id)
                            }
                        } else {
                            Intent(activity, LoginActivity::class.java).run {
                                startActivity(this)
                            }
                            showToast(resources.getString(R.string.login_tint))
                        }
                    }
                }
            }
        }

}